package com.cloudcc.mobile.view.aduit;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cloudcc.cloudframe.util.NearByUtil;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.basebean.BaseListEntity;
import com.cloudcc.mobile.dialog.AduitNearByPopupwindow;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.aduit.adapter.NearByAgentAdapter;
import com.cloudcc.mobile.view.aduit.adapter.NearByShopAdapter;
import com.cloudcc.mobile.view.aduit.bean.assetsBean;
import com.cloudcc.mobile.view.aduit.bean.shopBean;
import com.cloudcc.mobile.view.aduit.model.impl.AduitNearByModel;
import com.cloudcc.mobile.view.aduit.presenter.impl.AduitNearByPresenter;
import com.cloudcc.mobile.view.aduit.view.IAduitNearByView;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.nearby.MyOrientationListener;
import com.cloudcc.mobile.view.nearby.NearByMapActivity;

import org.kymjs.kjframe.ui.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * <pre>
 *     author : 92152
 *     e-mail : xxx@xx
 *     time   : 2020/04/03
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class AduitNearByMapActivity extends BaseActivity implements View.OnClickListener, AduitNearByPopupwindow.onItemPopupClick, IAduitNearByView {
    @Bind(R.id.near_by_back_iv)
    ImageView nearByBackIv;
    @Bind(R.id.near_by_list_iv)
    ImageView nearByListIv;
    @Bind(R.id.near_by_title_long_tv)
    TextView nearByTitleLongTv;
    @Bind(R.id.near_by_title_long_iv)
    ImageView nearByTitleLongIv;
    @Bind(R.id.near_by_title_long_layout)
    LinearLayout nearByTitleLongLayout;
    @Bind(R.id.near_by_title_lei_tv)
    TextView nearByTitleLeiTv;
    @Bind(R.id.near_by_title_lei_iv)
    ImageView nearByTitleLeiIv;
    @Bind(R.id.near_by_title_lei_layout)
    LinearLayout nearByTitleLeiLayout;
    @Bind(R.id.near_by_map_top_layout)
    RelativeLayout nearByMapTopLayout;
    @Bind(R.id.near_by_top_line)
    View nearByTopLine;
    @Bind(R.id.near_by_location_tv)
    TextView nearByLocationTv;
    @Bind(R.id.near_by_refresh_iv)
    ImageView nearByRefreshIv;
    @Bind(R.id.near_by_number_tv)
    TextView nearByNumberTv;
    @Bind(R.id.near_by_map)
    MapView nearByMap;
    @Bind(R.id.near_by_list)
    ListView nearByList;
    @Bind(R.id.near_by_custom_name_tv)
    TextView nearByCustomNameTv;
    @Bind(R.id.near_by_custom_long_tv)
    TextView nearByCustomLongTv;
    @Bind(R.id.near_by_detail_layout)
    LinearLayout nearByDetailLayout;
    @Bind(R.id.near_by_route_layout)
    LinearLayout nearByRouteLayout;
    @Bind(R.id.near_by_custom_layout)
    LinearLayout nearByCustomLayout;
    @Bind(R.id.near_by_map_all)
    LinearLayout nearByMapAll;
    @Bind(R.id.near_by_long_tv)
    TextView nearByLongTv;
    @Bind(R.id.near_by_object_tv)
    TextView nearByObjectTv;
    @Bind(R.id.near_by_nodata_layout)
    LinearLayout nearByNoData;

    private AduitNearByPopupwindow popupdis, popupobj;
    private LocationClient locationClient;
    private BaiduMap baiduMap;
    //是否是首次定位
    private boolean firstLocation;
    private BitmapDescriptor mCurrentMarker;
    private MyOrientationListener myOrientationListener;
    //当前经纬度
    private double mCurrentLantitude, mCurrentLongitude;
    //当前定位地址
    private String addressNow;
    //getRadius 获取定位精度,默认值0.0f
    private float mCurrentAccracy;
    //定位选择角度，设定图标方向
    private float mXDirection;
    // 当前定位的模式
    private MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
    private Bitmap bitmapDescriptor1, bitmapDescriptorSelect1;
    private BitmapDescriptor bitmapDescriptor, bitmapDescriptorSelect;

    private LatLng formlatLng;//起始经纬度
    private LatLng tolatLng;//目的地经纬度

//    private List<NearByMapInfo.NearByMapInfo2> lists = new ArrayList<>();

    public static boolean isMap = true;//判断当前显示的是否是地图，默认显示地图
    private NearByShopAdapter shopAdapter;
    private NearByAgentAdapter agentAdapter;
    private int marks;//1--打开第一个pop  2--打开第二个pop

    private String objects = "001";//默认门店 001：门店，002：营销资产
    private double distances = 3000;//默认初始3km

    private boolean isSelect = false;

    public AduitNearByPresenter aduitNearByPresenter;

//    public Dialog dialog;

    private ArrayList<com.cloudcc.mobile.view.aduit.bean.shopBean> shopBeans = new ArrayList<>();
    private ArrayList<com.cloudcc.mobile.view.aduit.bean.assetsBean> assetsBeans = new ArrayList<>();

    private ArrayList<shopBean> shopBeansNow = new ArrayList<>();
    private ArrayList<assetsBean> assetsBeansNow = new ArrayList<>();

    shopBean shopBean = new shopBean();
    assetsBean assetsBean = new assetsBean();

    boolean isFirstGetShopData = true;
    boolean isFirstGetAssetsData = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //此方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        initView();
        initLister();
        listtomap();
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_aduit_nearby_map;
    }


    /**
     * 初始化view、地图、定位
     */
    private void initView() {
        nearByTitleLeiTv.setText("门店");
        nearByObjectTv.setText("个门店");
//        dialog = ProgressDialogUtils.createLoadingDialog(this, "加载中,请稍后...");
        aduitNearByPresenter = new AduitNearByPresenter(this, new AduitNearByModel());
        popupdis = new AduitNearByPopupwindow(this, 1);//距离弹窗
        popupobj = new AduitNearByPopupwindow(this, 2);//对象弹窗
        bitmapDescriptor1 = BitmapFactory.decodeResource(getResources(), R.drawable.nearby_positionicon);
        shopAdapter = new NearByShopAdapter(this);
        agentAdapter = new NearByAgentAdapter(this);
        nearByList.setAdapter(shopAdapter);

        baiduMap = nearByMap.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15f);
        baiduMap.setMapStatus(msu);
        // 定位初始化
        locationClient = new LocationClient(this);
        firstLocation = true;
        // 设置定位的相关配置
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true);//打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);//间隔多少时间定位
        option.setAddrType("all");
        locationClient.setLocOption(option);


        //实现实位回调监听
        locationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                // map view 销毁后不在处理新接收的位置
                if (location == null || nearByMap == null) {
                    return;
                }
                mCurrentAccracy = location.getRadius();
                // 设置定位数据
                mCurrentLantitude = location.getLatitude();
                mCurrentLongitude = location.getLongitude();
                addressNow = location.getAddrStr();

                formlatLng = new LatLng(mCurrentLantitude, mCurrentLongitude);

                if (objects.equals("001")) {
                    if (isFirstGetShopData && formlatLng != null) {
                        isFirstGetShopData = false;
                        ApiGetShopData();
                    }
                } else if (objects.equals("002")) {
                    if (isFirstGetAssetsData && formlatLng != null) {
                        isFirstGetAssetsData = false;
                        ApiGetAssetsData();
                    }
                }
                /**
                 * 可以通过BDLocation配置如下参数
                 * 1.accuracy 定位精度
                 * 2.latitude 百度纬度坐标
                 * 3.longitude 百度经度坐标
                 * 4.satellitesNum GPS定位时卫星数目 getSatelliteNumber() gps定位结果时，获取gps锁定用的卫星数
                 * 5.speed GPS定位时速度 getSpeed()获取速度，仅gps定位结果时有速度信息，单位公里/小时，默认值0.0f
                 * 6.direction GPS定位时方向角度
                 * */

                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(mCurrentAccracy)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(mXDirection)
                        .latitude(mCurrentLantitude)
                        .longitude(mCurrentLongitude).build();

                //设置定位数据, 只有先允许定位图层后设置数据才会生效，参见 setMyLocationEnabled(boolean)
                baiduMap.setMyLocationData(locData);

                // 设置自定义图标
                BitmapDescriptor myMarker = BitmapDescriptorFactory
                        .fromResource(R.drawable.nearby_personalposition);

                //配置定位图层显示方式,三个参数的构造器
                /**
                 * 1.定位图层显示模式
                 * 2.是否允许显示方向信息
                 * 3.用户自定义定位图标
                 *
                 * */
                MyLocationConfiguration config = new MyLocationConfiguration(
                        mCurrentMode, true, myMarker);

                baiduMap.setMyLocationConfigeration(config);

                // 第一次定位时，将地图位置移动到当前位置
                if (firstLocation) {
                    addressNow = String.format(getResources().getString(R.string.near_by_now_location), addressNow);
                    nearByLocationTv.setText(addressNow);
                    firstLocation = false;
                    LatLng xy = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(xy);
                    baiduMap.animateMapStatus(status);
                }
            }
        });

    }

    /**
     * 初始化方向传感器
     */
    private void initOritationListener() {
        myOrientationListener = new MyOrientationListener(
                getApplicationContext());
        myOrientationListener
                .setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
                    @Override
                    public void onOrientationChanged(float x) {

                        mXDirection = x;

                        // 构造定位数据
                        MyLocationData locData = new MyLocationData.Builder()
                                .accuracy(mCurrentAccracy)
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                                .direction(mXDirection)
                                .latitude(mCurrentLantitude)
                                .longitude(mCurrentLongitude).build();
                        // 设置定位数据
                        baiduMap.setMyLocationData(locData);
                        // 设置自定义图标
                        BitmapDescriptor myMarker = BitmapDescriptorFactory
                                .fromResource(R.drawable.nearby_personalposition);

                        MyLocationConfiguration config = new MyLocationConfiguration(
                                mCurrentMode, true, myMarker);
                        baiduMap.setMyLocationConfigeration(config);

                    }
                });
    }

    private void initLister() {
        nearByTitleLongLayout.setOnClickListener(this);
        nearByTitleLeiLayout.setOnClickListener(this);
        nearByBackIv.setOnClickListener(this);
        nearByListIv.setOnClickListener(this);
        nearByDetailLayout.setOnClickListener(this);
        nearByRouteLayout.setOnClickListener(this);
        nearByRefreshIv.setOnClickListener(this);

        nearByList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(AduitNearByMapActivity.this, BeauInfoActivity.class);
                switch (objects) {
                    case "001":
                        intent.putExtra("beau.name", "门店");
                        intent.putExtra("beau.nameid", "201775E7E9EE71DQVM80");
                        intent.putExtra("beau.imageid", "cloudtab20");
                        intent.putExtra("beau.ismefollow", false);
                        intent.putExtra("beau.id", shopBeansNow.get(position).getId());
                        intent.putExtra("OBJID", "");
                        intent.putExtra("OBJNAME", "");
                        intent.putExtra("beau.edit", false);
                        startActivity(intent);
                        break;
                    case "002":
                        intent.putExtra("beau.name", "营销资产");
                        intent.putExtra("isAssets", true);
                        intent.putExtra("beau.nameid", "20176482973AACCaRHOl");
                        intent.putExtra("beau.imageid", "cloudtab12");
                        intent.putExtra("beau.ismefollow", false);
                        intent.putExtra("beau.id", assetsBeansNow.get(position).getId());
                        intent.putExtra("OBJID", "");
                        intent.putExtra("OBJNAME", "");
                        intent.putExtra("beau.edit", false);
                        startActivity(intent);
                        break;
                }
            }
        });

        initOritationListener();
        setMarkerClick();
    }

    @Override
    public void onClick(View v) {
        if (v == nearByTitleLongLayout) {
            if (popupdis.isShowing()) {
                popupdis.dismiss();
            } else {
                marks = 1;
                NearByUtil.startPropertyAnim(nearByTitleLongIv);
                popupdis.showPopupWindow(nearByMapAll, nearByBackIv.getWidth() + (nearByTitleLongLayout.getWidth() / 2), nearByMapTopLayout, NearByUtil.getStatusBarHeight(this));
            }
        }
        if (v == nearByTitleLeiLayout) {
            if (popupobj.isShowing()) {
                popupobj.dismiss();
            } else {
                marks = 2;
                NearByUtil.startPropertyAnim(nearByTitleLeiIv);
                popupobj.showPopupWindow(nearByMapAll, nearByBackIv.getWidth() + nearByTitleLongLayout.getWidth() + (nearByTitleLeiLayout.getWidth() / 2), nearByMapTopLayout, NearByUtil.getStatusBarHeight(this));
                popupobj.setDataToView();
            }
        }
        if (v == nearByBackIv) {
            finish();
        }
        if (v == nearByListIv) {
            if (isMap) {
                maptolist();
                if (objects.equals("001")) {
                    setShopListParger();
                } else if (objects.equals("002")) {
                    setAssetsListParger();
                }
            } else {
                listtomap();
                addInfosOverlay();
            }

        }
        if (v == nearByDetailLayout) {
            Intent intent = new Intent(AduitNearByMapActivity.this, BeauInfoActivity.class);
            switch (objects){
                case "001":
                    intent.putExtra("beau.name", "门店");
                    intent.putExtra("beau.nameid", "201775E7E9EE71DQVM80");
                    intent.putExtra("beau.imageid", "cloudtab20");
                    intent.putExtra("beau.ismefollow", false);
                    intent.putExtra("beau.id", shopBean.getId());
                    intent.putExtra("OBJID", "");
                    intent.putExtra("OBJNAME", "");
                    intent.putExtra("beau.edit", false);
                    startActivity(intent);
                    break;
                case "002":
                    intent.putExtra("beau.name", "营销资产");
                    intent.putExtra("isAssets", true);
                    intent.putExtra("beau.nameid", "20176482973AACCaRHOl");
                    intent.putExtra("beau.imageid", "cloudtab12");
                    intent.putExtra("beau.ismefollow", false);
                    intent.putExtra("beau.id", assetsBean.getId());
                    intent.putExtra("OBJID", "");
                    intent.putExtra("OBJNAME", "");
                    intent.putExtra("beau.edit", false);
                    startActivity(intent);
                    break;
            }
        }
        if (v == nearByRouteLayout) {
            if (NearByUtil.isInstallByRead("com.baidu.BaiduMap")) {
                NearByUtil.startBaiduMap(tolatLng.latitude + "", tolatLng.longitude + "", this);
            } else {
                Toast.makeText(this, R.string.gaodemaptoast, Toast.LENGTH_SHORT).show();
            }
        }
        if (v == nearByRefreshIv) {
            switch (objects) {
                case "001":
                    shopBeansNow.clear();
                    shopBeans.clear();
                    shopAdapter.clear();
                    ApiGetShopData();
                    break;
                case "002":
                    assetsBeansNow.clear();
                    assetsBeans.clear();
                    agentAdapter.clear();
                    ApiGetAssetsData();
                    break;
            }
        }
    }

    //列表页转地图界面
    private void listtomap() {
        nearByListIv.setImageResource(R.drawable.nearby_listlookover);
        nearByList.setVisibility(View.GONE);
        nearByNoData.setVisibility(View.GONE);
        nearByMap.setVisibility(View.VISIBLE);
        isMap = true;
    }

    //地图界面转列表页
    private void maptolist() {
        nearByListIv.setImageResource(R.drawable.nearby_maplookover);
        nearByCustomLayout.setVisibility(View.GONE);
        nearByMap.setVisibility(View.GONE);
        nearByList.setVisibility(View.VISIBLE);
        isMap = false;
    }

    /**
     * 顶部popup选择结果
     */
    @Override
    public void onItemPopupClick(int obj, int mark) {
        nearByCustomLayout.setVisibility(View.GONE);//隐藏显示的选中图层详细信息
        isSelect = false;//设置选择为未选择
        if (mark == 1) {
            switch (obj) {
                case R.string.near_by_1km:
                    distances = 1000;
                    break;
                case R.string.near_by_3km:
                    distances = 3000;
                    break;
                case R.string.near_by_5km:
                    distances = 5000;
                    break;
                case R.string.near_by_maxkm:
                    distances = 10000;
                    break;
            }
            if (objects.equals("001")) {
                filterShopData();
                if (isMap) {
                    addInfosOverlay();
                } else {
                    setShopListParger();
                }
            } else if (objects.equals("002")) {
                filterAssetsData();
                if (isMap) {
                    addInfosOverlay();
                } else {
                    setAssetsListParger();
                }
            }
            nearByTitleLongTv.setText(getString(obj));
            nearByLongTv.setText(getString(obj));
            popupdis.dismiss();
        } else {
            switch (obj) {
                case R.string.near_by_md:
                    objects = "001";
                    if (shopBeans == null || shopBeans.size() == 0) {
                        ApiGetShopData();
                    }
                    filterShopData();
                    if (isMap) {
                        addInfosOverlay();
                    } else {
                        setShopListParger();
                    }
                    break;
                case R.string.near_by_jxs:
                    objects = "002";
                    if (assetsBeans == null || assetsBeans.size() == 0) {
                        ApiGetAssetsData();
                    }
                    filterAssetsData();
                    if (isMap) {
                        addInfosOverlay();
                    } else {
                        setAssetsListParger();
                    }
                    break;
            }
            nearByTitleLeiTv.setText(getString(obj));
            nearByObjectTv.setText("个" + getString(obj));
            popupobj.dismiss();
        }

    }

    @Override
    protected void onStop() {
        // 关闭图层定位
        baiduMap.setMyLocationEnabled(false);
        locationClient.stop();
        myOrientationListener.stop();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在activity执行onDestroy时执行mMapView.onDestroy()
        nearByMap.onDestroy();
        nearByMap = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()
        nearByMap.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()
        nearByMap.onPause();
    }

    @Override
    protected void onStart() {
        // 如果要显示位置图标,必须先开启图层定位
        baiduMap.setMyLocationEnabled(true);
        if (!locationClient.isStarted()) {
            locationClient.start();
        }
        myOrientationListener.start();
        super.onStart();
    }


    /**
     * 初始化图层
     */
    public void addInfosOverlay() {
        baiduMap.clear();
        LatLng latLng = null;
        OverlayOptions overlayOptions = null;
        Marker marker = null;
        baiduMap.clear();
        switch (objects) {
            case "001":
                if (shopBeansNow != null && shopBeansNow.size() != 0) {

                    for (int n = shopBeansNow.size() - 1; n >= 0; n--) {
                        shopBean info = shopBeansNow.get(n);
                        // 位置
                        latLng = new LatLng(Double.valueOf(info.getDzzb().split(",", -1)[1]), Double.valueOf(info.getDzzb().split(",", -1)[0]));
                        // 图标
                        if (n == 0 && !isSelect) {//默认未做选择之前选中第一个
                            bitmapDescriptorSelect1 = BitmapFactory.decodeResource(getResources(), R.drawable.nearby_positionicon_selected);
                            bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(n + 1 + "", bitmapDescriptorSelect1, R.color.near_by_tubiao_text_color_select, AduitNearByMapActivity.this));
                        } else {
                            bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(n + 1 + "", bitmapDescriptor1, R.color.near_by_tubiao_text_color, AduitNearByMapActivity.this));
                        }
                        overlayOptions = new MarkerOptions().position(latLng)
                                .icon(bitmapDescriptor)
                                .title(n + 1 + "");//设置标题;
                        marker = (Marker) (baiduMap.addOverlay(overlayOptions));
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("info", info);
                        bundle.putString("title", n + 1 + "");
                        marker.setExtraInfo(bundle);
                        tolatLng = latLng;

                        if (n == 0 && !isSelect) {//默认未做选择之前显示第一个的详情信息
                            nearByCustomLayout.setVisibility(View.VISIBLE);
                            nearByCustomNameTv.setText((info.getName() == null ? "" : n + 1 + "." + info.getName()));
                            String distanceNow = String.format(getResources().getString(R.string.near_by_now_distance), getDistance(tolatLng, formlatLng) + "m");
                            nearByCustomLongTv.setText(distanceNow);
                            shopBean = info;
                        }
                    }
                }
                break;
            case "002":
                if (assetsBeansNow != null && assetsBeansNow.size() != 0) {

                    for (int n = assetsBeansNow.size() - 1; n >= 0; n--) {
                        assetsBean info = assetsBeansNow.get(n);
                        // 位置
                        latLng = new LatLng(Double.valueOf(info.getTfzb().split(",", -1)[1]), Double.valueOf(info.getTfzb().split(",", -1)[0]));
                        // 图标
                        if (n == 0 && !isSelect) {//默认未做选择之前选中第一个
                            bitmapDescriptorSelect1 = BitmapFactory.decodeResource(getResources(), R.drawable.nearby_positionicon_selected);
                            bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(n + 1 + "", bitmapDescriptorSelect1, R.color.near_by_tubiao_text_color_select, AduitNearByMapActivity.this));
                        } else {
                            bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(n + 1 + "", bitmapDescriptor1, R.color.near_by_tubiao_text_color, AduitNearByMapActivity.this));
                        }
                        overlayOptions = new MarkerOptions().position(latLng)
                                .icon(bitmapDescriptor)
                                .title(n + 1 + "");//设置标题;
                        marker = (Marker) (baiduMap.addOverlay(overlayOptions));
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("info", info);
                        bundle.putString("title", n + 1 + "");
                        marker.setExtraInfo(bundle);
                        tolatLng = latLng;

                        if (n == 0 && !isSelect) {//默认未做选择之前显示第一个的详情信息
                            nearByCustomLayout.setVisibility(View.VISIBLE);
                            nearByCustomNameTv.setText((info.getName() == null ? "" : n + 1 + "." + info.getName()));
                            String distanceNow = String.format(getResources().getString(R.string.near_by_now_distance), getDistance(tolatLng, formlatLng) + "m");
                            nearByCustomLongTv.setText(distanceNow);
                            assetsBean = info;
                        }
                    }
                }
                break;
        }
    }

    //设置图层点击事件
    private void setMarkerClick() {
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {
                isSelect = true;
                addInfosOverlay();
                switch (objects) {
                    case "001":
                        //获得marker中的数据
                        shopBean info = (shopBean) marker.getExtraInfo().get("info");
                        String titles = marker.getExtraInfo().getString("title");
                        // 位置
                        LatLng latLng = new LatLng(Double.valueOf(info.getDzzb().split(",", -1)[1]), Double.valueOf(info.getDzzb().split(",", -1)[0]));
                        bitmapDescriptorSelect1 = BitmapFactory.decodeResource(getResources(), R.drawable.nearby_positionicon_selected);
                        bitmapDescriptorSelect = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(titles, bitmapDescriptorSelect1, R.color.near_by_tubiao_text_color_select, AduitNearByMapActivity.this));
                        // 图标
                        OverlayOptions overlayOptions = new MarkerOptions().position(latLng)
                                .icon(bitmapDescriptorSelect)
                                .title(titles);//设置标题;
                        baiduMap.addOverlay(overlayOptions);
                        Marker marker2 = (Marker) (baiduMap.addOverlay(overlayOptions));
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("info", info);
                        bundle.putString("title", titles);
                        marker2.setExtraInfo(bundle);
                        tolatLng = latLng;

                        nearByCustomLayout.setVisibility(View.VISIBLE);
                        nearByCustomNameTv.setText((info.getName() == null ? "" : titles + "." + info.getName()));
                        String distanceNow = String.format(getResources().getString(R.string.near_by_now_distance), getDistance(tolatLng, formlatLng) + "m");
                        nearByCustomLongTv.setText(distanceNow);
                        shopBean = info;
                        break;
                    case "002":
                        //获得marker中的数据
                        assetsBean assetsInfo = (assetsBean) marker.getExtraInfo().get("info");
                        String assetsTitles = marker.getExtraInfo().getString("title");
                        // 位置
                        LatLng assetsLatLng = new LatLng(Double.valueOf(assetsInfo.getTfzb().split(",", -1)[1]), Double.valueOf(assetsInfo.getTfzb().split(",", -1)[0]));
                        bitmapDescriptorSelect1 = BitmapFactory.decodeResource(getResources(), R.drawable.nearby_positionicon_selected);
                        bitmapDescriptorSelect = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(assetsTitles, bitmapDescriptorSelect1, R.color.near_by_tubiao_text_color_select, AduitNearByMapActivity.this));
                        // 图标
                        OverlayOptions assetsOverlayOptions = new MarkerOptions().position(assetsLatLng)
                                .icon(bitmapDescriptorSelect)
                                .title(assetsTitles);//设置标题;
                        baiduMap.addOverlay(assetsOverlayOptions);
                        Marker assetsMarker2 = (Marker) (baiduMap.addOverlay(assetsOverlayOptions));
                        Bundle assetsBundle = new Bundle();
                        assetsBundle.putSerializable("info", assetsInfo);
                        assetsBundle.putString("title", assetsTitles);
                        assetsMarker2.setExtraInfo(assetsBundle);
                        tolatLng = assetsLatLng;

                        nearByCustomLayout.setVisibility(View.VISIBLE);
                        nearByCustomNameTv.setText((assetsInfo.getName() == null ? "" : assetsTitles + "." + assetsInfo.getName()));
                        String assetsDistanceNow = String.format(getResources().getString(R.string.near_by_now_distance), getDistance(tolatLng, formlatLng) + "m");
                        nearByCustomLongTv.setText(assetsDistanceNow);
                        assetsBean = assetsInfo;
                        break;
                }
                return true;
            }
        });
    }

    /**
     * 计算两点之间距离
     *
     * @return 米
     */
    private double getDistance(LatLng mudilng, LatLng melng) {

        double distanse = DistanceUtil.getDistance(mudilng, melng);
        distanse = Math.floor(distanse);
        return distanse;
    }

    public void changeAnima() {//顶部三角转回动画
        if (marks == 1) {
            NearByUtil.startPropertyAnim2(nearByTitleLongIv);
        } else if (marks == 2) {
            NearByUtil.startPropertyAnim2(nearByTitleLeiIv);
        }

    }


    /**
     * 请求门店数据
     */
    private void ApiGetShopData() {
        Map<String, String> params = new HashMap<>();
        params.put("serviceName", "cqueryWithRoleRight");
        params.put("objectApiName", "mendian");
        params.put("binding", RunTimeManager.getInstance().getServerBinding());
        params.put("expressions", "zt='正常' and dzzb is not null and is_deleted <> '1'");
        aduitNearByPresenter.inquireShopData(params);
    }

    /**
     * 请求营销资产数据
     */
    private void ApiGetAssetsData() {
        Map<String, String> params = new HashMap<>();
        params.put("serviceName", "cqueryWithRoleRight");
        params.put("objectApiName", "yxzc");
        params.put("binding", RunTimeManager.getInstance().getServerBinding());
        params.put("expressions", "zt='正常' and tfzb is not null and is_deleted <> '1'");
        aduitNearByPresenter.inquireAssetsData(params);
    }

    private void setShopListParger() {
        if (shopBeansNow == null || shopBeansNow.size() == 0) {
            nolist();
            return;
        }
        nearByList.setVisibility(View.VISIBLE);
        nearByNoData.setVisibility(View.GONE);
        shopAdapter.clear();
        agentAdapter.clear();
        nearByList.setAdapter(shopAdapter);
        shopAdapter.addData(shopBeansNow);
    }

    private void setAssetsListParger() {
        if (assetsBeansNow == null || assetsBeansNow.size() == 0) {
            nolist();
            return;
        }
        nearByList.setVisibility(View.VISIBLE);
        nearByNoData.setVisibility(View.GONE);
        shopAdapter.clear();
        agentAdapter.clear();
        nearByList.setAdapter(agentAdapter);
        agentAdapter.addData(assetsBeansNow);
    }

    //列表数据为空时
    private void nolist() {
        nearByList.setVisibility(View.GONE);
        nearByNoData.setVisibility(View.VISIBLE);
        nearByNumberTv.setText("0");
    }

    @Override
    public void showDialog(boolean isShow) {
//        if (isShow) {
//            dialog.show();
//        } else {
//            dialog.dismiss();
//        }
    }

    @Override
    public void inquireShopData(BaseListEntity<shopBean> entity) {
        shopBeans.clear();
        if (entity != null) {
            if (entity.getData().size() > 0) {
                for (int i = 0; i < entity.getData().size(); i++) {
                    if (entity.getData().get(i).getDzzb() != null && entity.getData().get(i).getDzzb().length() > 0) {
                        double toLongitude = Double.valueOf(entity.getData().get(i).getDzzb().split(",", -1)[0]);
                        double toLatitude = Double.valueOf(entity.getData().get(i).getDzzb().split(",", -1)[1]);
                        tolatLng = new LatLng(toLatitude, toLongitude);
                        shopBean shopBean = entity.getData().get(i);
                        shopBean.setDistance(getDistance(tolatLng, formlatLng));
                        shopBeans.add(shopBean);

                    } else {
                        shopBean shopBean = entity.getData().get(i);
                        shopBean.setDistance(-1);
                        shopBeans.add(shopBean);
                    }
                }
            } else {
                ViewInject.toast("没有门店数据");
            }
        }
        filterShopData();
        if (!isMap) {
            setShopListParger();
        } else {
            addInfosOverlay();
        }
    }

    @Override
    public void inquireAssetsData(BaseListEntity<assetsBean> entity) {
        assetsBeans.clear();
        if (entity != null) {
            if (entity.getData().size() > 0) {
                for (int i = 0; i < entity.getData().size(); i++) {
                    if (entity.getData().get(i).getTfzb() != null && entity.getData().get(i).getTfzb().length() > 0) {
                        double toLongitude = Double.valueOf(entity.getData().get(i).getTfzb().split(",", -1)[0]);
                        double toLatitude = Double.valueOf(entity.getData().get(i).getTfzb().split(",", -1)[1]);
                        tolatLng = new LatLng(toLatitude, toLongitude);
                        assetsBean assetsBean = entity.getData().get(i);
                        assetsBean.setDistance(getDistance(tolatLng, formlatLng));
                        assetsBeans.add(assetsBean);
                    } else {
                        assetsBean assetsBean = entity.getData().get(i);
                        assetsBean.setDistance(-1);
                        assetsBeans.add(assetsBean);
                    }
                }
            } else {
                ViewInject.toast("没有营销资产数据");
            }
        }
        filterAssetsData();
        if (!isMap) {
            setAssetsListParger();
        } else {
            addInfosOverlay();
        }
    }

    //过滤门店
    private void filterShopData() {
        shopBeansNow = new ArrayList<>();
        for (int i = 0; i < shopBeans.size(); i++) {
            if (shopBeans.get(i).getDistance() <= distances) {
                shopBeansNow.add(shopBeans.get(i));
            }
        }

        if (shopBeansNow != null) {
            nearByNumberTv.setText(shopBeansNow.size() + "");
        } else {
            nearByNumberTv.setText("0");
        }
    }

    //过滤营销资产
    private void filterAssetsData() {
        assetsBeansNow = new ArrayList<>();
        for (int i = 0; i < assetsBeans.size(); i++) {
            if (assetsBeans.get(i).getDistance() <= distances) {
                assetsBeansNow.add(assetsBeans.get(i));
            }
        }

        if (assetsBeansNow != null) {
            nearByNumberTv.setText(assetsBeansNow.size() + "");
        } else {
            nearByNumberTv.setText("0");
        }
    }
}
